/*
 * Copyright (C) 2008 Chris Bellew
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#import "iDynDNSSettingsView.h";
#import "iDynDNSSettings.h";
#import "iDynDNSController.h";
#import "IntervalPickerView.h"
#import <UIKit/UIPreferencesTable.h>
#import <UIKit/UIPreferencesTableCell.h>
#import <UIKit/UIPreferencesTextTableCell.h>


#define UIMouseUp 1<<6 //up within the active area 
#define UIMouseExitedUp 1<<7 //up outside active area


static iDynDNSSettingsView *_sharedInstance = nil;



@implementation iDynDNSSettingsView


+ (iDynDNSSettingsView *)sharedInstance
{
	if(!_sharedInstance) {
		_sharedInstance = [[self alloc] init];
	}
    return _sharedInstance;
}

-(id)init{
	_sharedInstance = self;
	
	struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
    rect.origin.x = rect.origin.y = 0.0f;

	_wiFiOn = [[iDynDNSSettings sharedInstance] localAddress] != nil;
	
	// Every 30 seconds, see if wifi status has changed
	timer = [NSTimer scheduledTimerWithTimeInterval: 30
                target: self
                selector: @selector(checkForWiFiChange:)
                userInfo: nil
                repeats: YES];
	[self checkForWiFiChange:nil];
	return [self initWithFrame:rect];
}

- (id) checkForWiFiChange:(NSTimer *)timer {
	BOOL changed = NO;
	[[iDynDNSSettings sharedInstance] getCurrentIP];
	if([[[iDynDNSSettings sharedInstance] localAddress] isEqualToString:@""]) {
		if(_wiFiOn) {
			[_updateIPButton setEnabled:NO];
			changed = YES;
		}
		_wiFiOn = NO;
	} else {
		if(!_wiFiOn) {
			[_updateIPButton setEnabled:YES];
			changed = YES;
		}
		_wiFiOn = YES;
	}
	if(changed) {
		[_prefTable reloadData];
	}
}

// designated initializer
-(id)initWithFrame:(CGRect) rect {
	self = [super initWithFrame: rect];
	_sharedInstance = self;
	
	_mainView = [[UITransitionView alloc] initWithFrame:rect];


	_navigationBar = [[UINavigationBar alloc] initWithFrame: CGRectMake(0.0f, 0.0f, rect.size.width, NAVBAR_HEIGHT)];
    [_navigationBar setDelegate:self];
    [_navigationBar enableAnimation];
   	UINavigationItem *navTitle;
   	navTitle = [[UINavigationItem alloc] initWithTitle: @"iDynDNS"];
   	[_navigationBar pushNavigationItem:navTitle];
    [_navigationBar setButton:0 enabled:false]; 
   
	[[iDynDNSSettings sharedInstance] getCurrentIP];
  	[[iDynDNSSettings sharedInstance] loadSettings];
  	if([[iDynDNSSettings sharedInstance] autoUpdate]) {
	  	[[iDynDNSController sharedInstance] addStatusBarImageNamed:@"iDynDNS" removeOnAbnormalExit:YES];
  	}
	_prefTable = [[UIPreferencesTable alloc] initWithFrame:CGRectMake(0.0, NAVBAR_HEIGHT, rect.size.width, rect.size.height - NAVBAR_HEIGHT)];
	[_prefTable setDelegate:self];
	[_prefTable setDataSource:self];
	
	[_mainView addSubview:_prefTable];

	[_prefTable reloadData];
	
	[self addSubview:_navigationBar];
	[self addSubview:_prefTable];

	return self;
}



#pragma mark Table Datasource Methods

- (int) numberOfGroupsInPreferencesTable: (UIPreferencesTable*)table
{
	return 2;
}

- (int) preferencesTable: (UIPreferencesTable*) table numberOfRowsInGroup: (int) group
{
	switch ( group ) {
	  case 0: 
		// general settings
		return 6;
	  case 1:
		// current ip & last update
		if([[iDynDNSSettings sharedInstance] lastUpdateDate] != nil) {
			return 2;
		} else {
			return 1;
		}
	}
}

- (UIPreferencesTableCell*)preferencesTable:(UIPreferencesTable*)table cellForGroup: (int)group
{
	
	switch (group) {
	  case 0: {
	  	return [[UIPreferencesTableCell alloc] init];
	  }
	}
	return nil;
}

- (UIPreferencesTableCell*) preferencesTable: (UIPreferencesTable*)table cellForRow: (int)row inGroup: (int)group
{
	switch(group) {
		case 0:
			switch(row) {
				case 0: {
					_usernameCell = [[UIPreferencesTextTableCell alloc] init];
					[_usernameCell setTitle:@"Username:"];
					[[_usernameCell textField] setText:[[iDynDNSSettings sharedInstance] username]];
					return _usernameCell;
				}
				case 1: {
					_passwordCell = [[UIPreferencesTextTableCell alloc] init];
					[_passwordCell setTitle:@"Password:"];
					[[_passwordCell textField] setSecureTextEntry:YES ];
					[[_passwordCell textField] setText:[[iDynDNSSettings sharedInstance] password]];
					return _passwordCell;
				}
			   	case 2: {
					_hostnameCell = [[UIPreferencesTextTableCell alloc] init];
					[_hostnameCell setTitle:@"Hostname:"];
					[[_hostnameCell textField] setText:[[iDynDNSSettings sharedInstance] hostname]];
					[[_hostnameCell textField] setPreferredKeyboardType: 3];
					[_hostnameCell setReturnAction:@selector(_removeKeyboard)];
			   		return _hostnameCell;
			   	}
			   	case 3: {
			   		_autoUpdateCell = [[UIPreferencesTextTableCell alloc] init];
			   		[_autoUpdateCell setTitle:@"Auto Update:"];
			   		_autoUpdateControl = [(UISwitchControl*)[UISwitchControl alloc ] initWithFrame:CGRectMake(210, 10, 30, 150) ];
				    if ([[iDynDNSSettings sharedInstance] autoUpdate]) {
				        [_autoUpdateControl setValue: 1.0 ];
				    } else {
				        [_autoUpdateControl setValue: 0.0 ];
				    }
				    [_autoUpdateControl setAlternateColors: NO ];
				    [_autoUpdateControl addTarget:self action:@selector(setAutoUpdate:) forEvents:UIMouseUp];
//				    [_autoUpdateControl addTarget:self action:@selector(setAutoUpdate:) forEvents:UIMouseExitedUp];
				    [_autoUpdateCell addSubview:_autoUpdateControl];
				    return _autoUpdateCell;
			   	
			   	}
			   	case 4: {
			   		_updateIntervalCell = [[UIPreferencesTableCell alloc] init];
			   		[_updateIntervalCell setTitle:[[NSString alloc] initWithFormat:@"Update Every: %@ minutes.", [[iDynDNSSettings sharedInstance] updateInterval]]];
			   		[_updateIntervalCell setShowDisclosure:YES];
			   		[_updateIntervalCell setDisclosureStyle: 0];
			   		[_updateIntervalCell setTapDelegate:self];
			   		return _updateIntervalCell;
			   	}
			   	case 5: {
					_updateCell = [[UIPreferencesTableCell alloc] init];
					CGRect buttonRect = CGRectMake(210, 9.0f, 95.0f, 32.0f);
				    _updateIPButton = [(UINavBarButton*)[UINavBarButton alloc] initWithFrame: 
					CGRectMake(buttonRect.origin.x - 100, buttonRect.origin.y, buttonRect.size.width, buttonRect.size.height)];
				    [_updateIPButton setAutosizesToFit: FALSE];
				    [_updateIPButton setNavBarButtonStyle: 0];
				    [_updateIPButton setTitle: @"Update"];
				    if([[[iDynDNSSettings sharedInstance] localAddress] isEqualToString:@""]) {
				    	[_updateIPButton setEnabled:NO];
				    }
				    [_updateCell addSubview:_updateIPButton];
				    [_updateIPButton addTarget:self action: @selector(updateIP) forEvents: 1];
			   		return _updateCell;
			   	}
			}
		case 1:
			switch(row) {
				case 0: {
					_currentIPCell = [[UIPreferencesTextTableCell alloc] init];
					[_currentIPCell setTitle:[@"Current IP: " stringByAppendingString:[[iDynDNSSettings sharedInstance] localAddress]]];
					return _currentIPCell;
				}
				case 1: {
					_lastUpdateDateCell = [[UIPreferencesTableCell alloc] init];
					[_lastUpdateDateCell setTitle:[NSString stringWithFormat:@"Last Update: %@", [[[iDynDNSSettings sharedInstance] lastUpdateDate] descriptionWithCalendarFormat:@"%b %d, %Y %I:%M %p" timeZone:nil locale:nil]]];
					return _lastUpdateDateCell;
				}
			}
	}
}


- (void)tableRowSelected:(NSNotification *)notification 
{
	if([_prefTable selectedRow] == 5) {
		[_prefTable selectRow:-1 byExtendingSelection:NO withFade:YES];
		[[iDynDNSController sharedInstance] showView:[IntervalPickerView sharedInstance] event:1];
	}
	
}

#pragma mark Accessor Methods

- (void)_removeKeyboard
{
	[_prefTable setKeyboardVisible: FALSE animated: TRUE];
}

#pragma mark Navigation Delegate

- (void)navigationBar:(UINavigationBar *)navbar buttonClicked:(int)button {
	switch( button ) {
		case 0:
			if ([_autoUpdateControl value] != 0.0) {
				[[iDynDNSSettings sharedInstance] setAutoUpdate:YES];
			} else {
				[[iDynDNSSettings sharedInstance] setAutoUpdate:NO];
			}   
	}
	
}

#pragma mark Other Methods


-(void)dealloc {
	
	[_navigationBar release];
	[_updateCell release];
	[_updateIntervalCell release];
    [_autoUpdateCell release];
    [_lastUpdateDateCell release];
	[_currentIPCell release];
	[_usernameCell release];
	[_passwordCell release];
	[_hostnameCell release];
	[_updateCell release];
	[_autoUpdateControl release];
	[_updateIPButton release];
	[_prefTable release];	
	[_mainView release];
	[[IntervalPickerView sharedInstance] release];
	[timer release];
    [super dealloc];
}

-(void)doUpdate {
	NSString *_statusCode = [[iDynDNSSettings sharedInstance] updateIP];
	[[iDynDNSController sharedInstance] closeProgressHUD];
	if([_statusCode isEqualToString:@"good"]) {
		[_prefTable reloadData];
	} else if(![_statusCode isEqualToString:@""]) {
		UIAlertSheet *alertSheet = [[UIAlertSheet alloc] initWithTitle:nil buttons:[NSArray arrayWithObjects:@"OK", nil] defaultButtonIndex:1 delegate:self context:self];
		[alertSheet setBodyText:[[[iDynDNSSettings sharedInstance] statusCodes] valueForKey:_statusCode]];
		[alertSheet popupAlertAnimated:YES];
	}
	_updateInProgress = NO;
}

-(void)updateIP {
	
	if(!_updateInProgress) {
		_updateInProgress = YES;
		[[iDynDNSSettings sharedInstance] setUsername:[[_usernameCell textField] text]];
		[[iDynDNSSettings sharedInstance] setPassword:[[_passwordCell textField] text]];
		[[iDynDNSSettings sharedInstance] setHostname:[[_hostnameCell textField] text]];
		
		[self performSelector:@selector(_removeKeyboard) withObject:nil afterDelay:0];
		[[iDynDNSController sharedInstance] openProgressHUD:@"Updating IP"];
		[self performSelector:@selector(doUpdate) withObject:nil afterDelay:0];
	}
}

- (void)alertSheet:(UIAlertSheet*)sheet buttonClicked:(int)button
{
  if ( button == 1 ){
    [sheet dismiss];
  }
}

- (UIPreferencesTable*)prefTable {
	return _prefTable;
}

-(void)setAutoUpdate:(id)ctl {
	// Also need to enable/disable the daemon here
	if ([_autoUpdateControl value] != 0.0) {
		[[iDynDNSSettings sharedInstance] setAutoUpdate:YES];
		[[iDynDNSController sharedInstance] addStatusBarImageNamed:@"iDynDNS" removeOnAbnormalExit:YES];
		NSString *res = [[iDynDNSController sharedInstance] executeCommand:@"/usr/local/bin/idyndns_daemon/idyndnsdctl start"];
		//NSLog(@"Enabling autoupdate");
	} else if ([_autoUpdateControl value] == 0.0) {
		[[iDynDNSSettings sharedInstance] setAutoUpdate:NO];
		[[iDynDNSController sharedInstance] removeStatusBarImageNamed:@"iDynDNS"];
		NSString *res = [[iDynDNSController sharedInstance] executeCommand:@"/usr/local/bin/idyndns_daemon/idyndnsdctl stop"];
		//NSLog(@"Disabling autoupdate");
	}
	[[iDynDNSSettings sharedInstance] saveSettings];

}

@end

